package com.sinba.common.utils;



import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by k000003 on 2016/6/28.
 */
public class HttpTest3 {
    public static void main(String[] arg)throws Exception{
        String key="wUPn6KarVhPdWv8W";
        String pw="kass";
       // System.out.println(new String(new BASE64Encoder().encode(Sha1(("123").getBytes(), "123".getBytes()))));
        System.out.println(sessionspace_acuqireOnceLoginUrl("Guest",key,pw));
       // System.out.println(filespace_acquireDownloadUrl("admin","/test1.txt","1","xhzRFEEjvhbTjFpz","kass"));


    }
    /****工具类**********/
    private static final String filespace_encodePath(String path) {
        if (path == null || path.length() == 0)
            return "";
        try {
            if (path.indexOf('/') < 0) {
                String url_encode = java.net.URLEncoder.encode(path, "UTF-8");
                return url_encode;
            }
            String str1 = path.substring(0, path.indexOf('/'));
            String str2 = path.substring(path.indexOf('/') + 1);
            String str1_encode = java.net.URLEncoder.encode(str1, "UTF-8");
            String str2_encode = filespace_encodePath(str2);
            return str1_encode + "/" + str2_encode;
        } catch (Exception e) {
            return "";
        }
    }
    private static byte[] Sha1(byte[] date,byte[] key)throws Exception{
        SecretKey secretKey = new SecretKeySpec(key, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(date);
        return rawHmac;
    }

    /**
     * 获取单次登录地址
     * @param userid
     * @param accesskey
     * @param password
     * @return
     * @throws Exception
     */
    public static String sessionspace_acuqireOnceLoginUrl(String userid, String accesskey, String password) throws Exception{
        if(userid==null || userid.length()==0){
            return null;
        }
        if(null == accesskey || 0 == accesskey.length()){
            return null;
        }
        String uri = "/kass/kapi/v1/sessionspace/user/" + URLEncoder.encode(userid, "UTF-8");
        URL url = new URL("http://demo.kass.com.cn:108" + uri);
        System.out.println(url.toString());
        HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String gmtdate = sdf.format(System.currentTimeMillis());
        String canonicalizedResource = uri;
        //若url存在参数，需要将参数格式标准化
        HashMap<String, String> url_paramap = new HashMap<String, String>();
        if(url_paramap.size()>0){
            Object[] keys = url_paramap.keySet().toArray();
            Arrays.sort(keys);
            for(int i=0; i<keys.length; i++){
                if(i==0)
                    canonicalizedResource += "?";
                else
                    canonicalizedResource += "&";
                canonicalizedResource += keys[i] + "=" + url_paramap.get(keys[i]);
            }
        }
        String verb = "POST";  // 请求方法类型
        //MessageDigest md = MessageDigest.getInstance("SHA-1");

        String signature = new String(new BASE64Encoder().encode(
               Sha1((verb.toUpperCase() + "\n" + gmtdate + "\n" + canonicalizedResource).getBytes(),
                        password.getBytes())));
        System.out.println("vrb="+verb.toUpperCase() + "\ntime=" + gmtdate + "\nurl=" + canonicalizedResource+"\npassword"+password);
        System.out.println("signature="+signature);

        //urlconn.addRequestProperty("date", gmtdate);
        urlconn.addRequestProperty("date", "date  Thu, 30 Jun 2016 03:25:22 GMT");

        //urlconn.addRequestProperty("authorization",  "KASS" + " " + accesskey + ":" + signature);
        urlconn.addRequestProperty("authorization",  "KASS kDBRFtXYeUh9cfPQ:T7tzBdVVTK0b/4jhagt+SwkHccg=");

        //System.out.println("date="+gmtdate);
        //System.out.println("authorization=KASS" + " " + accesskey + ":" + signature);
        //return null;
        urlconn.setRequestMethod(verb);
        urlconn.setConnectTimeout(6* 1000);
        if (urlconn.getResponseCode() == 200) {
            java.io.InputStream is = urlconn.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            is.close();
            byte[] bt = outSteam.toByteArray();
            return new String(bt, "UTF-8");
        } else if(urlconn.getResponseCode() == 401){
            throw new Exception("User unauthorized.");
        } else if(urlconn.getResponseCode() == 404){
            throw new Exception("User not found.");
        } else if(urlconn.getResponseCode() == 403){
            throw new Exception("User forbidden.");
        } else {
            throw new Exception("Internal server error.");
        }
    }

    public static String filespace_acquireDownloadUrl(String executor, String path, String version,
                                                     String accesskey, String password)throws Exception{

        if(executor==null || executor.length()==0){
            return null;
        }
        if(null == accesskey || 0 == accesskey.length()){
            return null;
        }
        String uri = "/kass/kapi/v1/filespace" + filespace_encodePath(path);
        //URL url = new URL("http://demo.kass.com.cn:108" + uri);


        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String gmtdate = sdf.format(System.currentTimeMillis());
        System.out.println("-date--"+gmtdate);
        String canonicalizedResource = uri;
        //若url存在参数，需要将参数格式标准化
        HashMap<String, String> url_paramap = new HashMap<String, String>();
        url_paramap.put("executor","admin");
        url_paramap.put("downloadversion","1");
        if(url_paramap.size()>0){
            Object[] keys = url_paramap.keySet().toArray();
            Arrays.sort(keys);
            for(int i=0; i<keys.length; i++){
                if(i==0)
                    canonicalizedResource += "?";
                else
                    canonicalizedResource += "&";
                canonicalizedResource += keys[i] + "=" + url_paramap.get(keys[i]);
            }
        }
        URL url = new URL("http://192.168.1.16:1088" + canonicalizedResource);
        HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
        String verb = "POST";  // 请求方法类型
        String signature = new String(new BASE64Encoder().encode(
                Sha1((verb.toUpperCase() + "\n" + gmtdate + "\n" + canonicalizedResource).getBytes(),
                        password.getBytes())));
        System.out.println("signature="+signature);
        urlconn.addRequestProperty("date", gmtdate);
        urlconn.addRequestProperty("authorization",  "KASS" + " " + accesskey + ":" + signature);
        //urlconn.addRequestProperty("executor","admin");
        //urlconn.addRequestProperty("downloadversion","1");
        urlconn.setRequestMethod(verb);
        urlconn.setConnectTimeout(6* 1000);
        System.out.println(canonicalizedResource);
        System.out.println(urlconn.getResponseCode());
        if (urlconn.getResponseCode() == 200) {
            java.io.InputStream is = urlconn.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            is.close();
            byte[] bt = outSteam.toByteArray();
            return new String(bt, "UTF-8");
        } else if(urlconn.getResponseCode() == 401){
            throw new Exception("User unauthorized.");
        } else if(urlconn.getResponseCode() == 404){
            throw new Exception("User not found.");
        } else if(urlconn.getResponseCode() == 403){
            throw new Exception("User forbidden.");
        } else {
            throw new Exception("Internal server error.");
        }


    }
}
